<template>
  <view class="index-container">
    <!-- 顶部导航栏 -->
    <view class="header">
      <view class="logo-area">
        <image class="logo" src="/static/images/logo.png" mode="aspectFit"></image>
        <text class="app-name">AI风格重绘</text>
      </view>
      <view class="search-bar" @click="navigateTo('/pages/search/search')">
        <text class="iconfont icon-search"></text>
        <text class="search-placeholder">搜索风格、作品</text>
      </view>
      <view class="notification-area">
        <notification-icon></notification-icon>
      </view>
    </view>
    
    <!-- 轮播图 -->
    <swiper class="banner-swiper" :indicator-dots="true" autoplay interval="3000" duration="500" indicator-color="rgba(255,255,255,0.5)" indicator-active-color="#FF69B4">
      <swiper-item v-for="(banner, index) in banners" :key="index">
        <view class="banner-item" @click="handleBannerClick(banner)">
          <image :src="banner.previewImage" mode="aspectFill"></image>
          <view class="banner-info">
            <text class="banner-title">{{ banner.title }}</text>
            <text class="banner-desc">{{ banner.description }}</text>
          </view>
        </view>
      </swiper-item>
    </swiper>
    
    <!-- 快捷功能区 -->
    <view class="quick-actions">
      <view class="action-item" @click="navigateTo('/pages/create/create')">
        <view class="action-icon create-icon">🎨</view>
        <text class="action-text">开始创作</text>
      </view>
      <view class="action-item" @click="navigateTo('/pages/style/list')">
        <view class="action-icon style-icon">🖌️</view>
        <text class="action-text">风格库</text>
      </view>
      <view class="action-item" @click="navigateTo('/pages/feed/feed')">
        <view class="action-icon discover-icon">🔍</view>
        <text class="action-text">发现</text>
      </view>
      <view class="action-item" @click="navigateTo('/pages/my/my')">
        <view class="action-icon profile-icon">👤</view>
        <text class="action-text">我的</text>
      </view>
    </view>
    
    <!-- 推荐风格区域 -->
    <view class="section">
      <view class="section-header">
        <text class="section-title">推荐风格</text>
        <text class="more-link" @click="navigateTo('/pages/style/list')">查看全部 ></text>
      </view>
      
      <scroll-view scroll-x class="style-scroll">
        <view 
          class="style-item" 
          v-for="(style, index) in recommendedStyles" 
          :key="index"
          @click="navigateToStyle(style.id)"
        >
          <image :src="style.previewImage" mode="aspectFill"></image>
          <text class="style-name">{{ style.name }}</text>
          <text class="style-desc">{{ style.description }}</text>
        </view>
      </scroll-view>
    </view>
    
    <!-- 热门组合区域 -->
    <view class="section">
      <view class="section-header">
        <text class="section-title">热门组合</text>
        <text class="more-link" @click="navigateTo('/pages/style/combinations')">查看全部 ></text>
      </view>
      
      <view class="combination-list">
        <view 
          class="combination-item" 
          v-for="(combo, index) in popularCombinations" 
          :key="index"
          @click="navigateTo(`/pages/style/combination?id=${combo.id}`)"
        >
          <view class="combo-tags">
            <text class="combo-tag" v-for="(tag, tagIndex) in (combo.tags || [])" :key="tagIndex">
              {{ tag }}
            </text>
          </view>
          <view class="combo-preview">
            <image 
              class="combo-image" 
              v-if="combo.previewImage"
              :src="combo.previewImage" 
              mode="aspectFill"
            ></image>
            <image 
              v-if="!combo.previewImage"
              class="combo-image"
              src="/static/images/default-style.png"
              mode="aspectFill"
            ></image>
          </view>
          <view class="combo-info">
            <text class="combo-name">{{ combo.name }}</text>
            <text class="combo-uses">{{ combo.usageCount || 0 }}人使用</text>
          </view>
        </view>
      </view>
    </view>
    
    <!-- 精选作品区域 -->
    <view class="section">
      <view class="section-header">
        <text class="section-title">精选内容</text>
        <text class="more-link" @click="navigateTo('/pages/feed/feed')">查看全部 ></text>
      </view>
      
      <view class="featured-grid">
        <view 
          class="featured-item" 
          v-for="(item, index) in featuredContent" 
          :key="index"
          @click="navigateToContent(item)"
        >
          <!-- 内容图片 -->
          <image :src="item.type === 'album' ? item.coverImage : item.resultImage" mode="aspectFill"></image>
          
          <!-- 内容类型标识 -->
          <view class="content-type-badge" v-if="item.type === 'album'">
            <text class="iconfont icon-album"></text>
          </view>
          
          <view class="featured-info">
            <!-- 标签展示 -->
            <view class="featured-tags">
              <!-- 专辑显示专辑标签 -->
              <text class="featured-tag" v-if="item.type === 'album'">
                专辑
              </text>
              <!-- 作品显示标签 -->
              <template v-else>
                <text class="featured-tag" v-for="(tag, tagIndex) in ((item.tags && item.tags.length > 0) ? item.tags.slice(0, 2) : [])" :key="tagIndex">
                  {{ tag }}
                </text>
                <!-- 如果没有标签，显示一个默认标签 -->
                <text class="featured-tag" v-if="!item.tags || item.tags.length === 0">
                  作品
                </text>
              </template>
            </view>
            
            <!-- 统计信息 -->
            <view class="featured-stats">
              <view class="featured-stat">
                <text class="iconfont icon-like"></text>
                <text>{{ item.likeCount || 0 }}</text>
              </view>
              <!-- 如果是专辑，显示图片数量 -->
              <view class="featured-stat" v-if="item.type === 'album'">
                <text class="iconfont icon-image"></text>
                <text>{{ item.imageCount || 0 }}</text>
              </view>
            </view>
          </view>
        </view>
      </view>
    </view>
    
    <!-- 新手教程区域 -->
    <view class="section tutorial-section">
      <view class="section-header">
        <text class="section-title">新手教程</text>
      </view>
      
      <view class="tutorial-steps">
        <view class="tutorial-step">
          <view class="step-number">1</view>
          <view class="step-content">
            <text class="step-title">上传图片</text>
            <text class="step-desc">选择你喜欢的照片上传</text>
          </view>
        </view>
        <view class="tutorial-step">
          <view class="step-number">2</view>
          <view class="step-content">
            <text class="step-title">选择风格</text>
            <text class="step-desc">从丰富的风格库中挑选喜欢的风格</text>
          </view>
        </view>
        <view class="tutorial-step">
          <view class="step-number">3</view>
          <view class="step-content">
            <text class="step-title">生成作品</text>
            <text class="step-desc">AI将为你创作独特的艺术作品</text>
          </view>
        </view>
        <view class="tutorial-step">
          <view class="step-number">4</view>
          <view class="step-content">
            <text class="step-title">分享收藏</text>
            <text class="step-desc">将作品分享给朋友或收藏到相册</text>
          </view>
        </view>
      </view>
      
      <button class="start-btn" @click="navigateTo('/pages/create/create')">立即开始</button>
    </view>
  </view>
</template>

<script>
import { homeApi, styleApi, feedApi, albumApi } from '@/utils/api.js';
import NotificationIcon from '@/components/notification/NotificationIcon.vue';

export default {
  components: {
    NotificationIcon
  },
  
  data() {
    return {
      // 轮播图数据
      banners: [],
      
      // 推荐风格
      recommendedStyles: [],
      
      // 热门组合
      popularCombinations: [],
      
      // 精选内容（作品和专辑混合）
      featuredContent: [],
      
      // 精选作品
      featuredWorks: [],
      
      // 精选专辑
      featuredAlbums: []
    }
  },
  onShow() {
    this.loadFeaturedContent();
  },
  onLoad() {
    this.loadBanners();
    this.loadRecommendedStyles();
    this.loadPopularCombinations();
    this.loadFeaturedContent();
  },
  
  methods: {
    // 加载轮播图数据
    loadBanners() {
      uni.showLoading({
        title: '加载中...'
      });
      
      homeApi.getBanners()
        .then(res => {
          if (res && res.code === 200) {
            this.banners = res.data || [];
          } else {
            uni.showToast({
              title: res?.message || '获取轮播图失败',
              icon: 'none'
            });
            console.error('获取轮播图失败:', res?.message);
          }
        })
        .catch(err => {
          console.error('获取轮播图失败', err);
          uni.showToast({
            title: '获取轮播图失败，请检查网络',
            icon: 'none'
          });
        })
        .finally(() => {
          uni.hideLoading();
        });
    },
    
    // 加载推荐风格
    loadRecommendedStyles() {
      styleApi.getRecommendedStyles()
        .then(res => {
          if (res && res.code === 200) {
            this.recommendedStyles = res.data || [];
          } else {
            uni.showToast({
              title: res?.message || '获取推荐风格失败',
              icon: 'none'
            });
            console.error('获取推荐风格失败:', res?.message);
          }
        })
        .catch(err => {
          console.error('获取推荐风格失败', err);
          uni.showToast({
            title: '获取推荐风格失败，请检查网络',
            icon: 'none'
          });
        });
    },
    
    // 加载热门组合
    loadPopularCombinations() {
      styleApi.getPopularCombinations()
        .then(res => {
          if (res && res.code === 200) {
            this.popularCombinations = res.data || [];
          } else {
            uni.showToast({
              title: res?.message || '获取热门组合失败',
              icon: 'none'
            });
            console.error('获取热门组合失败:', res?.message);
          }
        })
        .catch(err => {
          console.error('获取热门组合失败', err);
          uni.showToast({
            title: '获取热门组合失败，请检查网络',
            icon: 'none'
          });
        });
    },
    
    // 加载精选内容（作品和专辑混合）
    loadFeaturedContent() {
      // 显示加载中
      uni.showLoading({
        title: '加载中...'
      });
      
      // 同时加载作品和专辑
      Promise.all([
        this.loadFeaturedWorks(),
        this.loadFeaturedAlbums()
      ])
        .then(() => {
          // 合并作品和专辑数据
          this.mergeFeaturedContent();
        })
        .finally(() => {
          uni.hideLoading();
        });
    },
    
    // 合并作品和专辑数据
    mergeFeaturedContent() {
      // 将作品数据添加类型标识
      const works = this.featuredWorks.map(work => ({
        ...work,
        type: 'work'
      }));
      
      // 将专辑数据添加类型标识
      const albums = this.featuredAlbums.map(album => ({
        ...album,
        type: 'album'
      }));
      
      // 合并数据
      const merged = [...works, ...albums];
      
      // 按创建时间排序（降序）
      merged.sort((a, b) => {
        const timeA = new Date(a.createTime || 0).getTime();
        const timeB = new Date(b.createTime || 0).getTime();
        return timeB - timeA;
      });
      
      // 只取前8个内容
      this.featuredContent = merged.slice(0, 8);
    },
    
    // 加载精选作品
    loadFeaturedWorks() {
      return new Promise((resolve, reject) => {
        feedApi.getFeaturedWorks()
          .then(res => {
            if (res && res.code === 200) {
              this.featuredWorks = res.data || [];
              resolve(this.featuredWorks);
            } else {
              console.error('获取精选作品失败:', res?.message);
              resolve([]);
            }
          })
          .catch(err => {
            console.error('获取精选作品失败', err);
            resolve([]);
          });
      });
    },
    
    // 加载精选专辑
    loadFeaturedAlbums() {
      return new Promise((resolve, reject) => {
        // 使用专辑API获取精选专辑
        albumApi.getAlbumList({ page: 1, size: 5 })
          .then(res => {
            if (res && res.code === 200) {
              this.featuredAlbums = res.data?.list || [];
              resolve(this.featuredAlbums);
            } else {
              console.error('获取精选专辑失败:', res?.message);
              resolve([]);
            }
          })
          .catch(err => {
            console.error('获取精选专辑失败', err);
            resolve([]);
          });
      });
    },
    
    // 处理轮播图点击
    handleBannerClick(banner) {
      switch (banner.linkType) {
        case 'style':
          this.navigateToStyle(banner.linkId);
          break;
        case 'activity':
          this.navigateTo(`/pages/activity/style?id=${banner.linkId}`);
          break;
        case 'feature':
          this.navigateTo(`/pages/feature/style?id=${banner.linkId}`);
          break;
        default:
          break;
      }
    },
    
    // 导航到风格详情
    navigateToStyle(styleId) {
      uni.navigateTo({
        url: `/pages/style/style?id=${styleId}`
      });
    },
    
    // 根据内容类型导航到不同页面
    navigateToContent(item) {
      if (item.type === 'album') {
        uni.navigateTo({
          url: `/pages/album-detail/album-detail?id=${item.id}`
        });
      } else {
        uni.navigateTo({
          url: `/pages/detail/detail?id=${item.id}`
        });
      }
    },
    
    // 应用风格组合
    applyCombination(combo) {
      uni.navigateTo({
        url: `/pages/create/create?comboId=${combo.id}`
      });
    },
    
    // 导航到作品详情
    navigateToDetail(id) {
      uni.navigateTo({
        url: `/pages/detail/detail?id=${id}`
      });
    },
    
    // 页面导航
    navigateTo(url) {
      // 判断是否是tabBar页面
      const tabBarPages = ['/pages/feed/feed', '/pages/create/create', '/pages/my/my'];
      
      if (tabBarPages.includes(url)) {
        // 如果是tabBar页面，使用switchTab
        uni.switchTab({
          url: url
        });
      } else {
        // 非tabBar页面，使用navigateTo
        uni.navigateTo({
          url: url
        });
      }
    }
  }
}
</script>

<style>
.index-container {
  background-color: #f8f8f8;
  min-height: 100vh;
}

/* 顶部导航栏 */
.header {
  display: flex;
  align-items: center;
  justify-content: space-between;
  padding: 20rpx 30rpx;
  background-color: #fff;
  box-shadow: 0 2rpx 10rpx rgba(0, 0, 0, 0.05);
}

.logo-area {
  display: flex;
  align-items: center;
}

.logo {
  width: 60rpx;
  height: 60rpx;
  margin-right: 10rpx;
}

.app-name {
  font-size: 32rpx;
  font-weight: bold;
  color: #333;
}

.search-bar {
  flex: 1;
  display: flex;
  align-items: center;
  background-color: #f5f5f5;
  border-radius: 30rpx;
  padding: 10rpx 20rpx;
  margin: 0 20rpx;
}

.search-placeholder {
  font-size: 26rpx;
  color: #999;
}

.notification-area {
  margin-left: 20rpx;
  width: 60rpx;
  height: 60rpx;
  display: flex;
  justify-content: center;
  align-items: center;
}

/* 轮播图 */
.banner-swiper {
  height: 300rpx;
  margin-bottom: 20rpx;
}

.banner-item {
  position: relative;
  width: 100%;
  height: 100%;
}

.banner-item image {
  width: 100%;
  height: 100%;
}

.banner-info {
  position: absolute;
  bottom: 0;
  left: 0;
  right: 0;
  padding: 20rpx 30rpx;
  background: linear-gradient(to top, rgba(0,0,0,0.7), transparent);
}

.banner-title {
  font-size: 32rpx;
  font-weight: bold;
  color: #fff;
  margin-bottom: 10rpx;
  display: block;
}

.banner-desc {
  font-size: 24rpx;
  color: rgba(255,255,255,0.8);
}

/* 快捷功能区 */
.quick-actions {
  display: flex;
  background-color: #fff;
  padding: 30rpx 0;
  margin-bottom: 20rpx;
}

.action-item {
  flex: 1;
  display: flex;
  flex-direction: column;
  align-items: center;
}

.action-icon {
  width: 100rpx;
  height: 100rpx;
  border-radius: 50%;
  display: flex;
  justify-content: center;
  align-items: center;
  font-size: 40rpx;
  margin-bottom: 15rpx;
}

.create-icon {
  background-color: rgba(255, 105, 180, 0.1);
  color: #FF69B4;
}

.style-icon {
  background-color: rgba(64, 158, 255, 0.1);
  color: #409EFF;
}

.discover-icon {
  background-color: rgba(103, 194, 58, 0.1);
  color: #67C23A;
}

.profile-icon {
  background-color: rgba(230, 162, 60, 0.1);
  color: #E6A23C;
}

.action-text {
  font-size: 26rpx;
  color: #333;
}

/* 通用区域样式 */
.section {
  background-color: #fff;
  padding: 30rpx;
  margin-bottom: 20rpx;
}

.section-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 20rpx;
}

.section-title {
  font-size: 32rpx;
  font-weight: bold;
  color: #333;
}

.more-link {
  font-size: 26rpx;
  color: #999;
}

/* 推荐风格区域 */
.style-scroll {
  white-space: nowrap;
}

.style-item {
  display: inline-block;
  width: 250rpx;
  margin-right: 20rpx;
  border-radius: 12rpx;
  overflow: hidden;
}

.style-item image {
  width: 100%;
  height: 330rpx;
  border-radius: 12rpx;
}

.style-name {
  font-size: 28rpx;
  color: #333;
  font-weight: bold;
  margin-top: 15rpx;
  display: block;
  white-space: normal;
}

.style-desc {
  font-size: 24rpx;
  color: #999;
  margin-top: 5rpx;
  display: block;
  white-space: normal;
}

/* 热门组合区域 */
.combination-list {
  display: flex;
  flex-wrap: wrap;
  margin: 0 -10rpx;
}

.combination-item {
  width: calc(50% - 20rpx);
  margin: 10rpx;
  background-color: #f9f9f9;
  border-radius: 12rpx;
  padding: 20rpx;
  box-shadow: 0 2rpx 10rpx rgba(0, 0, 0, 0.05);
  transition: all 0.3s ease;
  box-sizing: border-box;
  height: 280rpx;
  display: flex;
  flex-direction: column;
}

.combination-item:active {
  transform: scale(0.98);
  box-shadow: 0 1rpx 5rpx rgba(0, 0, 0, 0.1);
}

.combo-tags {
  display: flex;
  flex-wrap: wrap;
  margin-bottom: 15rpx;
}

.combo-tag {
  font-size: 22rpx;
  color: #FF69B4;
  background-color: rgba(255, 105, 180, 0.1);
  padding: 4rpx 12rpx;
  border-radius: 20rpx;
  margin-right: 10rpx;
  margin-bottom: 10rpx;
}

.combo-preview {
  display: flex;
  margin-bottom: 15rpx;
  flex: 1;
  justify-content: space-between;
}

.combo-image {
  width: 100%;
  height: 150rpx;
  border-radius: 8rpx;
  object-fit: cover;
}

.combo-info {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-top: auto;
}

.combo-name {
  font-size: 26rpx;
  color: #333;
  font-weight: bold;
  width: 65%;
  white-space: nowrap;
  overflow: hidden;
  text-overflow: ellipsis;
}

.combo-uses {
  font-size: 22rpx;
  color: #999;
}

/* 精选作品区域 */
.featured-grid {
  display: flex;
  flex-wrap: wrap;
  margin: 0 -10rpx;
}

.featured-item {
  width: calc(50% - 20rpx);
  margin: 10rpx;
  border-radius: 12rpx;
  overflow: hidden;
  position: relative;
}

.featured-item image {
  width: 100%;
  height: 400rpx;
  border-radius: 12rpx;
}

.featured-info {
  position: absolute;
  bottom: 0;
  left: 0;
  right: 0;
  padding: 15rpx;
  background: linear-gradient(to top, rgba(0,0,0,0.7), transparent);
  display: flex;
  justify-content: space-between;
  align-items: center;
}

.featured-tags {
  display: flex;
}

.featured-tag {
  font-size: 22rpx;
  color: #fff;
  background-color: rgba(255, 255, 255, 0.2);
  padding: 4rpx 12rpx;
  border-radius: 20rpx;
  margin-right: 10rpx;
}

.featured-stats {
  display: flex;
}

.featured-stat {
  display: flex;
  align-items: center;
  font-size: 22rpx;
  color: #fff;
}

/* 新手教程区域 */
.tutorial-section {
  background-color: #fff8fa;
  border-radius: 12rpx;
}

.tutorial-steps {
  margin-bottom: 30rpx;
}

.tutorial-step {
  display: flex;
  align-items: center;
  margin-bottom: 20rpx;
}

.step-number {
  width: 60rpx;
  height: 60rpx;
  border-radius: 50%;
  background-color: #FF69B4;
  color: #fff;
  font-size: 28rpx;
  font-weight: bold;
  display: flex;
  justify-content: center;
  align-items: center;
  margin-right: 20rpx;
}

.step-content {
  flex: 1;
}

.step-title {
  font-size: 28rpx;
  font-weight: bold;
  color: #333;
  margin-bottom: 5rpx;
  display: block;
}

.step-desc {
  font-size: 24rpx;
  color: #999;
}

.start-btn {
  background-color: #FF69B4;
  color: #fff;
  font-size: 30rpx;
  padding: 20rpx 0;
  border-radius: 40rpx;
  width: 80%;
  margin: 0 auto;
}
</style>
